package com.zhangxuehai.pdfviewer.ui;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.zhangxuehai.android.pdfviewer.PDFView;
import com.zhangxuehai.android.pdfviewer.annotation.eraser.MarkEraserStrategy;
import com.zhangxuehai.android.pdfviewer.annotation.eraser.PenEraserStrategy;
import com.zhangxuehai.android.pdfviewer.annotation.eraser.RectEraser;
import com.zhangxuehai.android.pdfviewer.annotation.pen.Pen;
import com.zhangxuehai.android.pdfviewer.annotation.pen.PenBuilder;
import com.zhangxuehai.android.pdfviewer.listener.OnDrawListener;
import com.zhangxuehai.android.pdfviewer.listener.OnTapListener;
import com.zhangxuehai.android.pdfviewer.util.FitPolicy;
import com.zhangxuehai.pdfviewer.R;

/**
 * @author 章学海
 * @date 2020/3/5
 */
public class PdfControlView extends ConstraintLayout {
    public interface Call{
        void onForward();
        void onCollect(boolean collect);
        void onNote();
    }

    @Nullable
    PDFView pdfView;
    @Nullable
    PDFView.Configurator configurator;

    PDFView pdfThumbnailView;

    StatusView underline,strikethrough,highlight,pen,eraser,thumbnail,more;
    StatusView clean,forward,collect,note;
    StatusView[] bottomAtions;
    PdfPenPickView penPickView;
    ConstraintLayout pdfMoreLayout;
    TextView page;
    Call call;


    public PdfControlView(@NonNull Context context) {
        this(context,null);
    }

    public PdfControlView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        inflate(context, R.layout.view_pdf_control,this);
        init();
    }

    void init(){
        underline       = findViewById(R.id.pdf_underline);
        strikethrough   = findViewById(R.id.pdf_strikethrough);
        highlight       = findViewById(R.id.pdf_highlight);
        pen             = findViewById(R.id.pdf_pen);
        eraser          = findViewById(R.id.pdf_eraser);
        thumbnail       = findViewById(R.id.pdf_thumbnail);
        more            = findViewById(R.id.pdf_more);

        clean           = findViewById(R.id.pdf_clean);
        forward         = findViewById(R.id.pdf_forward);
        collect         = findViewById(R.id.pdf_collect);
        note            = findViewById(R.id.pdf_note);

        page            = findViewById(R.id.pdf_page);

        pdfThumbnailView= findViewById(R.id.pdf_thumbnail_view);
        pdfThumbnailView.setMinZoom(1F);
        pdfThumbnailView.setMidZoom(1F);
        pdfThumbnailView.setMaxZoom(1F);
        pdfThumbnailView.useBestQuality(false);

        pdfMoreLayout   = findViewById(R.id.pdf_more_layout);

        underline       .setOnClickListener(buttomAcitonClikc);
        strikethrough   .setOnClickListener(buttomAcitonClikc);
        highlight       .setOnClickListener(buttomAcitonClikc);
        pen             .setOnClickListener(buttomAcitonClikc);
        eraser          .setOnClickListener(buttomAcitonClikc);
        thumbnail       .setOnClickListener(buttomAcitonClikc);
        more            .setOnClickListener(buttomAcitonClikc);

        clean           .setOnClickListener(moreActionClick);
        forward         .setOnClickListener(moreActionClick);
        collect         .setOnClickListener(moreActionClick);
        note            .setOnClickListener(moreActionClick);

        bottomAtions = new StatusView[]{underline,strikethrough,highlight,pen,eraser,thumbnail,more};

        penPickView = findViewById(R.id.penPickView);
        penPickView.setPickCall(penPickCall);
    }

    OnClickListener buttomAcitonClikc = new OnClickListener() {
        @Override
        public void onClick(View v) {
            StatusView view = (StatusView) v;
            boolean check = !view.isCheck();
            for (StatusView bottomAtion : bottomAtions) {
                bottomAtion.setCheck(false);
            }
            setViewerMode();
            view.setCheck(check);
            int id = v.getId();
            if(id == R.id.pdf_pen){
                onPen(check);
            }else if (id == R.id.pdf_underline){
                onUnderline(check);
            }else if (id == R.id.pdf_strikethrough){
                onStrikethrough(check);
            }else if (id == R.id.pdf_highlight){
                onHighlight(check);
            }else if (id == R.id.pdf_eraser){
                onEraser(check);
            }else if (id == R.id.pdf_thumbnail){
                onThumbnail(check);
            }else if (id == R.id.pdf_more){
                onMore(check);
            }
        }
    };
    OnClickListener moreActionClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            if(id == R.id.pdf_clean){
                onClean();
            }else if(id == R.id.pdf_forward){
                onForward();
            }else if(id == R.id.pdf_collect){
                onCollect(!((StatusView)v).isCheck());
            }else if(id == R.id.pdf_note){
                onNote();
            }
        }
    };

    void onPen(boolean check){
        if(check){
            penPickView.setVisibility(VISIBLE);
        }else{
            setViewerMode();
        }
    }
    void onUnderline(boolean check){
        if(pdfView!=null){
            if(check){
                pdfView.setMarkMode(PenBuilder.underlinePenBuilder().setColor(Color.BLACK).build());
            }else{
                setViewerMode();
            }
        }
    }
    void onStrikethrough(boolean check){
        if(pdfView!=null){
            if(check){
                pdfView.setMarkMode(PenBuilder.strikethroughPenBuilder().setColor(Color.RED).build());
            }else{
                setViewerMode();
            }
        }
    }
    void onHighlight(boolean check){
        if(pdfView!=null){
            if(check){
                pdfView.setMarkMode(PenBuilder.selectedPenBuilder().setColor(Color.parseColor("#33FFFF00")).build());
            }else{
                setViewerMode();
            }
        }
    }
    void onEraser(boolean check){
        if(pdfView!=null){
            if(check){
                pdfView.setEraserMode(new RectEraser(80,80,true,new MarkEraserStrategy(),new PenEraserStrategy()));
            }else{
                setViewerMode();
            }
        }
    }
    void onThumbnail(boolean check){
        if(pdfView!=null){
            if(check){
                openThumbnail();
            }else{
                closeThumbnail();
            }
        }
    }
    void openThumbnail(){
        pdfThumbnailView.setVisibility(VISIBLE);
        if(!pdfThumbnailView.isRecycled()){
            pdfThumbnailView.recycle();
        }
        PDFView.Configurator tc = pdfThumbnailView.fromSource(configurator.getDocumentSource());
        tc.password(configurator.getPassword());
        //滚动方向
        tc.swipeHorizontal(true);
        //滚动完成后自动滚动到当前页适当的显示位置
        tc.pageSnap(false);
        //护眼模式
        //configurator.eyeMode(true);
        //设置2pdf页面间距
        tc.spacing(2);
        tc.defaultPage(pdfView.getCurrentPage());
        tc.onDrawAll(new OnDrawListener() {
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            Paint bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            {
                bgPaint.setColor(Color.parseColor("#33002222"));
            }
            @Override
            public void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage) {
                paint.setTextSize(Math.min(pageWidth, pageHeight) / 3);
                String text = String.valueOf(displayedPage + 1);
                float size = paint.measureText(text);
                canvas.drawText(text, (pageWidth - size) / 2, pageHeight / 2, paint);
                if (displayedPage == pdfView.getCurrentPage()) {
                    canvas.drawRect(new RectF(0, 0, pageWidth, pageHeight), bgPaint);
                }
            }
        });
        tc.onTap(new OnTapListener() {
            @Override
            public boolean onTap(MotionEvent e) {
                int page = pdfThumbnailView.getTapPage(e);
                pdfView.jumpTo(page, false);
                pdfThumbnailView.postInvalidate();
                return true;
            }
        });
        //适配策略
        tc.pageFitPolicy(FitPolicy.HEIGHT);
        tc.enableAnnotationRendering(false);
        tc.linkHandler(null);
        tc.load();
    }
    void closeThumbnail(){
        thumbnail.setCheck(false);
        pdfThumbnailView.setVisibility(GONE);
        if(!pdfThumbnailView.isRecycled()){
            pdfThumbnailView.recycle();
        }
    }
    void onMore(boolean check){
        if(pdfView!=null){
            if(check){
                pdfMoreLayout.setVisibility(VISIBLE);
            }else{
                closeMore();
            }
        }
    }
    void closeMore(){
        more.setCheck(false);
        pdfMoreLayout.setVisibility(GONE);
    }
    void onClean(){
        pdfView.removeAnnotion(pdfView.getCurrentPage());
    }
    void onForward(){
        if(call!=null){
            call.onForward();
        }
    }
    void onCollect(boolean collect){
        if(call!=null){
            call.onCollect(collect);
        }
    }
    void onNote(){
        if(call!=null){
            call.onNote();
        }
    }

    PdfPenPickView.PickCall penPickCall = new PdfPenPickView.PickCall() {
        float[] penWidths = new float[]{0.5f, 0.75f, 1.0f};
        @Override
        public void onPick(int color, int width) {
            if(pdfView!=null){
                Pen.WritePen pen = PenBuilder.brushPenBuilder().setColor(color).setPenWidthScale(penWidths[width]).build();
                pdfView.setPenMode(pen);
            }
        }
    };

    /**设置阅读模式*/
    void setViewerMode(){
        closeThumbnail();
        closeMore();
        penPickView.setVisibility(GONE);
        if(pdfView!=null){
            pdfView.setViewerMode();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            closeThumbnail();
            closeMore();
        }
        return super.onTouchEvent(event);
    }

    /**用于绑定pdfview控制
     * @param pdfView
     * @param configurator 用于缩略图*/
    public void bindPdfView(PDFView pdfView, PDFView.Configurator configurator){
        this.pdfView = pdfView;
        this.configurator = configurator;
    }

    public void setCall(Call call) {
        this.call = call;
    }
    public void setCollect(boolean collect){
        this.collect.setCheck(collect);
    }
    public void setNoted(boolean noted){this.note.setCheck(noted);}
    public void onPage(int curPage,int allPage){
        page.setVisibility(VISIBLE);
        page.setText(curPage+"/"+allPage);
    }

    @Override
    protected void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
}
